using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using Rest;

namespace Rest.Http
{
    /// <summary>
    /// Encoding: "application/x-www-form-urlencoded"
    /// </summary>
    /// <remarks>
    /// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    /// </remarks> 
    public class FormUrlEncoded : HttpContentType  
    {
        #region Properties
        private String contentType = "application/x-www-form-urlencoded";

        /// <summary>
        /// The content type for this instance (application/x-www-form-urlencoded)
        /// </summary>
        public sealed override String ContentType
        {
            get { return contentType; }
            set { contentType = value; }
        }
        #endregion

        /// <summary>
        /// Writes request body to the supplied stream
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="parameters"></param>
        /// <param name="dataItems"></param>
        /// <param name="characterEncoding"></param>
        public sealed override void WriteRequestBody(
            Stream stream,
            RestParameterCollection parameters,
            RestDataItemCollection dataItems,
            Encoding characterEncoding)
        {
            if (parameters != null && parameters.Count > 0)
            {
                String parameterString;
                Byte[] parameterBytes;
                Byte[] newlineBytes = characterEncoding.GetBytes("\r\n");

                IRestParameter parameter = null;

                for (Int32 i = 0; i < parameters.Count; i++)
                {
                    parameter = parameters[i];
                    parameterString =
                        String.Format(
                        "{0}={1}{2}",
                        HttpUtility.UrlPathEncode(parameter.Name),
                        HttpUtility.UrlPathEncode(parameter.Value),
                        i < parameters.Count - 1 ? "&": String.Empty);

                    parameterBytes = characterEncoding.GetBytes(parameterString);

                    stream.Write(parameterBytes, 0, parameterBytes.Length);
                }

                stream.Write(newlineBytes, 0, newlineBytes.Length); 
            }
        }
    }
}
